package com.mtt.erp.goods.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.mtt.erp.common.domain.MttErpResponse;
import com.mtt.erp.common.domain.QueryRequest;
import com.mtt.erp.common.exception.MttErpException;
import com.mtt.erp.common.utils.MttErpUtil;
import com.mtt.erp.common.utils.SortUtil;
import com.mtt.erp.common.excel.ExcelUtils;
import com.mtt.erp.goods.domain.PGoods;
import com.mtt.erp.goods.dao.PGoodsMapper;
import com.mtt.erp.goods.dto.PGoodsDto;
import com.mtt.erp.goods.dto.PGoodsExcelDto;
import com.mtt.erp.goods.service.IPGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author Orange
 */
@Service
@Slf4j
public class PGoodsServiceImpl extends ServiceImpl<PGoodsMapper, PGoods> implements IPGoodsService {
    @Value("${erp.max.batch.insert.num}")
    private int batchInsertMaxNum;

    @Override
    public IPage<PGoods> findGoods(QueryRequest request, PGoodsDto pGoodsDto) {
        LambdaQueryWrapper<PGoods> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pGoodsDto.getMaa01())) {
            queryWrapper.eq(PGoods::getMaa01, pGoodsDto.getMaa01());
        }
        if (StringUtils.isNotBlank(pGoodsDto.getCreateTimeFrom()) && StringUtils.isNotBlank(pGoodsDto.getCreateTimeTo())) {
            queryWrapper.ge(PGoods::getMaacdate, pGoodsDto.getCreateTimeFrom())
                        .le(PGoods::getMaacdate, pGoodsDto.getCreateTimeTo());
        }
         /*String roleId = MttErpUtil.getCurrentUser().getRoleId();
         if(roleId.equals("")){}*/// 获取总后台数据根据角色判断
        Page<PGoods> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, true);
        return this.page(page, queryWrapper);
    }

    @Override
    public List<PGoods> findGoodsList(QueryRequest request, PGoodsDto pGoodsDto) {
        LambdaQueryWrapper<PGoods> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pGoodsDto.getMaa01())) {
            queryWrapper.eq(PGoods::getMaa01, pGoodsDto.getMaa01());
        }
        if (StringUtils.isNotBlank(pGoodsDto.getCreateTimeFrom()) && StringUtils.isNotBlank(pGoodsDto.getCreateTimeTo())) {
            queryWrapper.ge(PGoods::getMaacdate, pGoodsDto.getCreateTimeFrom())
                    .le(PGoods::getMaacdate, pGoodsDto.getCreateTimeTo());
        }
        return this.list(queryWrapper);
    }

    @Override
    @Transactional
    public void createGoods(PGoods goods) {
        goods.setMaacdate(LocalDateTime.now());
        //商品是属于哪一个用户的
        Long currentUserId = MttErpUtil.getCurrentUser().getUserId();
        goods.setMaacuser(currentUserId.toString());
        this.save(goods);
    }

    @Override
    @Transactional
    public void updateGoods(PGoods goods)  {

        Long currentUserId = MttErpUtil.getCurrentUser().getUserId();
        goods.setMaamdate(LocalDateTime.now());
        goods.setMaamuser(currentUserId.toString());

        this.updateById(goods);
    }

    @Override
    @Transactional
    public void putAway(String[] goodsIds) {
        List<PGoods> goodsgList = Lists.newArrayList();
        for(String id:goodsIds){
            //lombok 构造方法的使用
            PGoods putAwayGoods = PGoods.builder().maa01(id).maaacti("1").build();
            goodsgList.add(putAwayGoods);
        }
        this.updateBatchById(goodsgList);
    }

    @Override
    public void saleOut(String[] goodsIds) {
        List<PGoods> goodsgList = Lists.newArrayList();
        for(String id:goodsIds){
            PGoods putAwayGoods = PGoods.builder().maa01(id).maaacti("0").build();
            goodsgList.add(putAwayGoods);
        }
        this.updateBatchById(goodsgList);
    }

    @Override
    public void batchInsert(List<PGoods> list) {
            int total = list.size();
            int max = batchInsertMaxNum;
            int count = total / max;
            int left = total % max;
            int length;
            if (left == 0) length = count;
            else length = count + 1;
            for (int i = 0; i < length; i++) {
                int start = max * i;
                int end = max * (i + 1);
                if (i != count) {
                    log.info("正在插入商品第" + (start + 1) + " ~ " + end + "条记录 ······");
                    saveBatch(list, end);
                } else {
                    end = total;
                    log.info("正在插入商品第" + (start + 1) + " ~ " + end + "条记录 ······");
                    saveBatch(list, end);
                }
            }


    }

    @Override
    public MttErpResponse improtByExcel(MultipartFile file) throws MttErpException {
            ExcelUtils.importExcelBefore(file);
            // 开始导入操作
            long beginTimeMillis = System.currentTimeMillis();
            final List<PGoodsExcelDto> data = Lists.newArrayList();
            final List<Map<String, Object>> error = Lists.newArrayList();
            try {
                ExcelKit.$Import(PGoodsExcelDto.class).readXlsx(file.getInputStream(), new ExcelReadHandler<PGoodsExcelDto>() {
                    @Override
                    public void onSuccess(int sheet, int row, PGoodsExcelDto goods) {
                        // 数据校验成功时，加入集合
                        //test.setCreateTime(new Date());
                        data.add(goods);
                    }
                    @Override
                    public void onError(int sheet, int row, List<ExcelErrorField> errorFields) {
                        // 数据校验失败时，记录到 error集合
                        error.add(ImmutableMap.of("row", row, "errorFields", errorFields));
                    }
                });
            } catch (IOException e) {
                log.error("Excel数据导入异常");
            }
            if (!data.isEmpty()) {
                // 将合法的记录批量入库
                // this.iPGoodsService.batchInsert(data);
            }
            long time = ((System.currentTimeMillis() - beginTimeMillis));
            ImmutableMap<String, Object> result = ImmutableMap.of(
                    "time", time,
                    "data", data,
                    "error", error
            );
            return new MttErpResponse().data(result);
        }
}
